package kevin.bigdata.spark.wc

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

/**
 * @author: kevin  
 * @date: 11:16 2021/3/26
 */
object Spark02_WordCount {
  def main(args: Array[String]): Unit = {
    // application
    // spark framework

    // TODO 建立和SPark框架的连接
    // JDBC：Connection
    val sparConf = new SparkConf().setMaster("local").setAppName("WordCount").set("spark.testing.memory","2147480000")
    val sc = new SparkContext(sparConf)

    // TODO 执行业务操作
    val lines: RDD[String] = sc.textFile("data")

    val words: RDD[String] = lines.flatMap(_.split(" "))

    val wordToOne = words.map(word => (word, 1))

    val wordGroup: RDD[(String, Iterable[(String, Int)])] = wordToOne.groupBy(t => t._1)

    val wordToCount = wordGroup.map{
      case(word, list) => {
        list.reduce(
          (t1,t2) => {
            (t1._1, t1._2 + t2._2)
          }
        )
      }
    }

    val array: Array[(String, Int)] = wordToCount.collect()

    array.foreach(println)

    // TODO 关闭连接
    sc.stop()
  }
}
